package com.boot.mgt.service.impl

import com.alibaba.fastjson.JSON
import com.boot.config.ParamConfig
import com.boot.config.datasource.OracleDb
import com.boot.core.result.MsgBean
import com.boot.core.result.ResultEnum
import com.boot.core.result.ResultTo
import com.boot.core.util.*
import com.boot.mgt.controller.app.vo.PoliceAddReportVo
import com.boot.mgt.controller.web.vo.EditAccidentVo
import com.boot.mgt.dao.mysql.*
import com.boot.mgt.dao.oracle.OracleTAcdFileMapper
import com.boot.mgt.model.*
import com.boot.mgt.model.vo.ExcelCTPoliceVo
import com.boot.mgt.model.vo.ExcelDateVo
import com.boot.mgt.model.vo.PoliceAccident
import com.boot.mgt.service.TaAccidentService
import com.boot.mgt.service.TaHmsPushService
import com.boot.mgt.service.TaPoliceService
import com.boot.mgt.service.TaPoliceSituationMonitoringService
import com.github.pagehelper.PageHelper
import com.github.pagehelper.PageInfo
import com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImpl
import org.apache.commons.lang3.StringUtils
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import tk.mybatis.mapper.entity.Example
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.http.HttpServletResponse

@AutoJsonRpcServiceImpl
@Service
class TaAccidentServiceImpl : TaAccidentService {

    @Autowired
    protected lateinit var accidentMapper: TaAccidentMapper

    @Autowired
    protected lateinit var accidentReportMapper: TaAccidentReportMapper

    @Autowired
    protected lateinit var accidentImageMapper: TaAccidentImageMapper

    @Autowired
    protected lateinit var accidentReportAssignMapper: TaAccidentReportAssignMapper

    @Autowired
    protected lateinit var districtMapper: TaDistrictMapper

    @Autowired
    protected lateinit var streetMapper: TaStreetMapper

    @Autowired
    protected lateinit var addressMapper: TaAddressMapper

    @Autowired
    private lateinit var activemqManager: ActivemqManager

    @Autowired
    private lateinit var taPoliceMapper: TaPoliceMapper

    @Autowired
    private lateinit var ondutyAccidentMapper: TaOndutyAccidentMapper

    @Autowired
    private lateinit var ondutyMobileMapper: TaOndutyMobileMapper

    @Autowired
    private lateinit var threadPoolTaskExecutor: ThreadPoolTaskExecutor

    @Autowired
    private lateinit var policeLogMapper: TaAccidentPoliceLogMapper

    @Autowired
    private lateinit var accidentService: TaAccidentService

    @Autowired
    private lateinit var positionApi: PositionApi

    @Autowired
    private lateinit var paramConfig: ParamConfig

    @Autowired
    private lateinit var taPoliceSituationMonitoringService: TaPoliceSituationMonitoringService

    @Autowired
    private lateinit var taPoliceService: TaPoliceService

    @Autowired
    protected lateinit var accidentVehicleMapper: TaAccidentVehicleMapper

    @Autowired
    protected lateinit var accidentPersonnelMapper: TaAccidentPersonnelMapper

    @Autowired
    protected lateinit var taHmsPushService: TaHmsPushService

    /**
     *传入案件(第三方)
     */
    @Transactional
    override fun designate(accident_report_id: Int, police_type: Int, police_number: String): ResultTo {

        log.info("收到报警信息,报警ID:{},分配警员类型:{}", accident_report_id, police_type)
        val date = FORMAT.format(Date())

        val taAccidentReport = accidentReportMapper.selectByPrimaryKey(accident_report_id)
        var selectPoliceNumber = ""
        if (police_type == 1) {
            TaOndutyAccident().apply {
                attendedDate = date
                this.policeNumber = police_number
                this.xqdw = taAccidentReport.xzqh
                val ondutyAccident = ondutyAccidentMapper.selectOne(this)

                var monitorMap: HashMap<String, Any?> = hashMapOf<String, Any?>()
                monitorMap.put("regionId", taAccidentReport.xzqh)
                monitorMap.put("casesAcceptedCalled", 1)
                taPoliceSituationMonitoringService.doMonitorAction(monitorMap)

                if (ondutyAccident == null) {
                    return ResultTo(ResultEnum.OPERATION_FAILED, "没有找到今日值班的事故中队警员")
                } else {
                    selectPoliceNumber = ondutyAccident.policeNumber ?: ""
                }
            }

        } else if (police_type == 2) {
            TaOndutyMobile().apply {
                attendedDate = date
                this.policeNumber = police_number
                this.xqdw = taAccidentReport.xqdw
                val taOndutyMobile = ondutyMobileMapper.selectOne(this)
                if (taOndutyMobile == null) {
                    return ResultTo(ResultEnum.OPERATION_FAILED, "没有找到今日值班的移动中队警员")
                } else {
                    selectPoliceNumber = taOndutyMobile.policeNumber ?: ""
                }
            }
        }

        TaPolice().apply {
            policeNumber = selectPoliceNumber
//            taPoliceMapper.selectOne(this) ?: return ResultTo(ResultEnum.OPERATION_FAILED, "该警员编号不存在")
            taPoliceService.searchPoliceById(policeNumber) ?: return ResultTo(ResultEnum.OPERATION_FAILED, "该警员编号不存在")
        }
        var addressTemp: String?
        accidentReportMapper.selectByPrimaryKey(accident_report_id)?.apply {
            if (this.accidentId != -1) {
                return ResultTo(ResultEnum.OPERATION_FAILED, "该案件已经指派警员")
            }
            addressTemp = address
            TaAccident().let {
                it.state = 1
                it.addTime = Date()
                it.xqdw = taAccidentReport.xqdw
                it.xzqh = taAccidentReport.xzqh // 案件分派增加行政区划功能
                it.dealTime = Date()
                accidentMapper.insertSelective(it)
                accidentId = it.id
                accidentReportMapper.updateByPrimaryKeySelective(this)
            }
            TaAccidentReportAssign().apply {
                accidentReportId = accident_report_id
                addTime = Date()
                hasAccepted = 2
                reportSource = 1
                assignedPoliceNumber = selectPoliceNumber
                accidentReportAssignMapper.insertSelective(this)
                MsgBean().apply {
                    policeNumber = selectPoliceNumber
                    accidentReportId = accident_report_id
                    put("address", addressTemp ?: "")
                    put("taAccidentReportId", accident_report_id)
                    activemqManager.send(this)
                }
            }
        }

        var policeLog = TaAccidentPoliceLog()
        policeLog.addTime = Date()
        policeLog.policeNumber = ManagerKit.getPoliceNumber()
        policeLog.type = 3
        policeLog.reportId = accident_report_id
        policeLog.content = "designate to->$police_number"
        policeLogMapper.insertSelective(policeLog)

        return ResultTo()
    }

    /**
     *交警同意或者拒绝接受案件(APP)
     */
    override fun policeAccept(has_accepted: Int, accident_report_id: Int): ResultTo {
        TaAccidentReportAssign().apply {
            this.accidentReportId = accident_report_id
            this.assignedPoliceNumber = ManagerKit.getPoliceNumber()
            this.hasAccepted = 2
            accidentReportAssignMapper.selectOne(this)?.let {
                if (it.hasAccepted == 3) {
                    return ResultTo(ResultEnum.OPERATION_FAILED, "该案件已失效")
                }
                it.hasAccepted = if (has_accepted == 1) {
                    accidentReportMapper.selectByPrimaryKey(accident_report_id).apply {
                        TaAccident().apply {
                            id = accidentId
                            state = 2
                            it.assignedPoliceAcceptTime = Date()
                            accidentMapper.updateByPrimaryKeySelective(this)
                        }
                        var monitorMap: HashMap<String, Any?> = hashMapOf<String, Any?>()
                        monitorMap.put("regionId", xzqh)
                        monitorMap.put("casesAcceptedAction", 1)//出警量
                        taPoliceSituationMonitoringService.doMonitorAction(monitorMap)
                    }
                    1
                } else {
                    0
                }
                accidentReportAssignMapper.updateByPrimaryKeySelective(it)
                return ResultTo()
            }
            log.info("没有在ta_accident_report_assign中找到对应的accident_report_id:${accident_report_id}数据")
        }
        return ResultTo(ResultEnum.OPERATION_FAILED)
    }

    /**
     *交警同意或者拒绝接受案件(APP)
     */
    override fun policeAcceptRpc(has_accepted: Int, accident_report_id: Int, police_number: String): ResultTo {
        TaAccidentReportAssign().apply {
            this.accidentReportId = accident_report_id
            this.assignedPoliceNumber = police_number
            this.hasAccepted = 2
            accidentReportAssignMapper.selectOne(this)?.let {
                if (it.hasAccepted == 3) {
                    return ResultTo(ResultEnum.OPERATION_FAILED, "该案件已失效")
                }
                it.hasAccepted = if (has_accepted == 1) {
                    accidentReportMapper.selectByPrimaryKey(accident_report_id).apply {
                        TaAccident().apply {
                            id = accidentId
                            state = 2
                            it.assignedPoliceAcceptTime = Date()
                            accidentMapper.updateByPrimaryKeySelective(this)
                        }
                        var monitorMap: HashMap<String, Any?> = hashMapOf<String, Any?>()
                        monitorMap.put("regionId", xzqh)
                        monitorMap.put("casesAcceptedAction", 1)//出警量
                        taPoliceSituationMonitoringService.doMonitorAction(monitorMap)
                    }
                    1
                } else {
                    0
                }
                accidentReportAssignMapper.updateByPrimaryKeySelective(it)
                return ResultTo()
            }
            log.info("没有在ta_accident_report_assign中找到对应的accident_report_id:${accident_report_id}数据")
        }
        return ResultTo(ResultEnum.OPERATION_FAILED)
    }

    /**
     * 转发警员列表
     */
    override fun forwardPoliceList(name: String?): ResultTo {
        val policeNumber: String? = ManagerKit.getPoliceNumber()
        val policeData = taPoliceService.searchPoliceById(policeNumber)

        val regionLikeCondition = taPoliceService.consRegion(ManagerKit.getOrgNum())

        val sql: String = " select " +
                " t.user_id, " +
                " t.user_name, " +
                " t.full_name, " +
                " t.region_id, " +
                " t.empower, " +
                " t.management, " +
                " ug.name, " +
                " ug.role, " +
                " ug.role_extend, " +
                " rg.level as region_level " +
                " from app_user t " +
                " left join user_group ug on ug.id=t.group_id " +
                " left join region_glbm rg on rg.id=t.region_id " +
                " where 1=1 " +
                " and t.region_id like'" + regionLikeCondition + "' " +
//                " and t.group_id!='"+ policeData["group_id"] as Long? +"' " +
                " and t.group_id!='5' " +
                " and ug.role='user' "

        var result: List<MutableMap<String, Any>> = arrayListOf<MutableMap<String, Any>>()

        result = taPoliceService.searchPoliceBySql(sql)

        var policeList = arrayListOf<TaPolice>()
        result.forEach { r ->
            var police = TaPolice()
            police?.policeNumber = r["user_name"] as String?
            police?.name = r["full_name"] as String?
            police?.xqdw = r["region_id"] as String?
            policeList.add(police)
        }

        return ResultTo().setData("policeList", policeList)

        /*val example = Example(TaPolice::class.java)
        val criteria = example.createCriteria()
                .andEqualTo("level", 1)
                .andEqualTo("xqdw", ManagerKit.getOrgNum())
        if (!name.isNullOrBlank()) {
            criteria.andLike("name", "%$name%")
        }
        val policeList = taPoliceMapper.selectByExample(example)
        val policeListNew = arrayListOf<TaPolice>()
        for (taPolice in policeList) {
            if (taPolice.policeNumber != ManagerKit.getPoliceNumber()) {
                policeListNew.add(taPolice)
            }
        }
        return ResultTo().setData("policeList", policeListNew)*/
    }

    /**
     * 转发警员列表
     */
    override fun forwardPoliceListRpc(name: String?, police_number: String?, org_num: String?): ResultTo {
        val policeNumber: String? = police_number
        val policeData = taPoliceService.searchPoliceById(policeNumber)

        val regionLikeCondition = taPoliceService.consRegion(org_num as String)

        val sql: String = " select " +
                " t.user_id, " +
                " t.user_name, " +
                " t.full_name, " +
                " t.region_id, " +
                " t.empower, " +
                " t.management, " +
                " ug.name, " +
                " ug.role, " +
                " ug.role_extend, " +
                " rg.level as region_level " +
                " from app_user t " +
                " left join user_group ug on ug.id=t.group_id " +
                " left join region_glbm rg on rg.id=t.region_id " +
                " where 1=1 " +
                " and t.region_id like'" + regionLikeCondition + "' " +
//                " and t.group_id!='"+ policeData["group_id"] as Long? +"' " +
                " and t.group_id!='5' " +
                " and ug.role='user' "

        var result: List<MutableMap<String, Any>> = arrayListOf<MutableMap<String, Any>>()

        result = taPoliceService.searchPoliceBySql(sql)

        var policeList = arrayListOf<TaPolice>()
        result.forEach { r ->
            var police = TaPolice()
            police?.policeNumber = r["user_name"] as String?
            police?.name = r["full_name"] as String?
            police?.xqdw = r["region_id"] as String?
            policeList.add(police)
        }

        return ResultTo().setData("policeList", policeList)
    }

    /**
     * 转发
     */
    override fun policeForward(police_number_session: String, police_number: String, accident_report_id: Int): ResultTo {

        TaPolice().apply {
            this.policeNumber = police_number_session
            taPoliceService.searchPoliceById(police_number_session)
                    ?: return ResultTo(ResultEnum.OPERATION_FAILED, "选取的警员不存在")
        }

        TaAccidentReportAssign().apply {
            val example = Example(TaAccidentReportAssign::class.java)
            example.createCriteria()
                    .andEqualTo("accidentReportId", accident_report_id)
                    .andEqualTo("assignedPoliceNumber", police_number_session)
                    .andNotEqualTo("hasAccepted", 3)
                    .andNotEqualTo("hasAccepted", 4)
            accidentReportAssignMapper.selectOneByExample(example)?.let {
                it.hasAccepted = 4
                accidentReportAssignMapper.updateByPrimaryKey(it)
                this.id = null
                this.accidentReportId = accident_report_id
                this.assignedPoliceNumber = police_number
                this.hasAccepted = 2
                this.reportSource = 2
                this.addTime = Date()
                accidentReportAssignMapper.insert(this)
                activemqManager.delete(police_number_session, accident_report_id)
                MsgBean().apply {
                    policeNumber = police_number
                    accidentReportId = accident_report_id
                    accidentReportMapper.selectByPrimaryKey(accident_report_id)?.apply {
                        put("address", address ?: "")
                        put("taAccidentReportId", accident_report_id)
                    }
                    activemqManager.send(this)
                }
                return ResultTo()
            }
        }
        return ResultTo(ResultEnum.OPERATION_FAILED)
    }

    /**
     *重新分配警员(第三方)
     */
    @Transactional
    override fun assign(assignedPoliceNumber: String, accidentReportId: Int): ResultTo {
        TaAccidentReportAssign().apply {
            this.accidentReportId = accidentReportId
            accidentReportAssignMapper.select(this)?.let {
                val accidentReportOne = it[0]
                accidentReportOne.assignedPoliceNumber = assignedPoliceNumber
                accidentReportOne.hasAccepted = 2
                accidentReportAssignMapper.updateByPrimaryKeySelective(accidentReportOne)
                val accidentReport = accidentReportMapper.selectByPrimaryKey(accidentReportId)
                MsgBean().apply {
                    policeNumber = assignedPoliceNumber
                    this.accidentReportId = accidentReportId
                    put("address", accidentReport.address!!)
                    put("taAccidentReportId", accidentReportId)
                    activemqManager.send(this)
                }
                return ResultTo()
            }
            log.info("没有在taAccidentReportAssign中找到对应的accidentReportId:${accidentReportId}数据")
            return ResultTo(ResultEnum.PARAM_ERROR)
        }
        return ResultTo(ResultEnum.OPERATION_FAILED)
    }

    @Transactional
    @Suppress("NestedLambdaShadowedImplicitParameter", "NestedLambdaShadowedImplicitParameter")
    override fun policeAddReport(taAccident: TaAccident, isAddPaper: Boolean, isWebEdit: Boolean): ResultTo {
        log.info("收到数据:${JSON.toJSONString(taAccident)}")
        var regionId: String? = ""
        taAccident.id?.let {
            taAccident.dealTime = Date()
            if (!isAddPaper) {
                selectPosition(taAccident, false)
                if (isWebEdit) {
                    log.debug("WEB编辑案件")
                    val one = accidentMapper.selectByPrimaryKey(taAccident.id)
                    taAccident.state = one.state
                    taAccident.addTime = one.addTime
                    accidentMapper.updateByPrimaryKey(taAccident)
                } else {
                    log.debug("APP上传案件")
                    TaAccidentReport().apply {
                        this.accidentId = taAccident.id
                        accidentReportMapper.selectOne(this)?.let {
                            regionId = it.xzqh
                            if (taAccident.subType == 1) {
                                //此处须手动调用同一
                                accidentService.policeAccept(1, it.id!!)
                            }
                            TaAccidentReportAssign().apply {
                                this.accidentReportId = it.id
                                this.assignedPoliceNumber = ManagerKit.getPoliceNumber()
                                this.hasAccepted = 1
                                accidentReportAssignMapper.selectOne(this)?.let {
                                    if (it.reportSource == 2) {
                                        this.assignedPoliceNumber = null
                                        accidentReportAssignMapper.select(this).apply {
                                            for (taAccidentReportAssign in this) {
                                                taAccidentReportAssign.reportSource = 3
                                                accidentReportAssignMapper.updateByPrimaryKeySelective(taAccidentReportAssign)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    taAccident.state = 3
                    taAccident.policeReportTime = Date()
                    accidentMapper.updateByPrimaryKeySelective(taAccident)
                    var monitorMap: HashMap<String, Any?> = hashMapOf<String, Any?>()
                    monitorMap.put("regionId", regionId)
                    if (taAccident.dealType as Int == 1) {// 受理
                        monitorMap.put("dealAccepted", 1)
                    } else if (taAccident.dealType as Int == 2) {// 快赔
                        monitorMap.put("dealFastPay", 1)
                    } else if (taAccident.dealType as Int == 3) {// 自行协商
                        monitorMap.put("dealToNegotiate", 1)
                    } else if (taAccident.dealType as Int == 4) {// 其他
                        monitorMap.put("dealOthers", 1)
                    }
                    taPoliceSituationMonitoringService.doMonitorAction(monitorMap)
                }
            } else {
                log.debug("第三方上传责任书")
                taAccident.state = 4
                taAccident.paperTime = Date()
                accidentMapper.updateByPrimaryKeySelective(taAccident)
            }
            return ResultTo().apply {
                this["taAccidentId"] = taAccident.id!!
            }
        }
        log.info("ID为Null")
        return ResultTo(ResultEnum.PARAM_ERROR)
    }

    @Transactional
    @Suppress("NestedLambdaShadowedImplicitParameter", "NestedLambdaShadowedImplicitParameter")
    override fun policeAddReportRpc(taAccident: TaAccident, isAddPaper: Boolean, isWebEdit: Boolean, police_number: String): ResultTo {
        log.info("收到数据:${JSON.toJSONString(taAccident)}")
        var regionId: String? = ""
        taAccident.id?.let {
            taAccident.dealTime = Date()
            if (!isAddPaper) {
                selectPosition(taAccident, false)
                if (isWebEdit) {
                    log.debug("WEB编辑案件")
                    val one = accidentMapper.selectByPrimaryKey(taAccident.id)
                    taAccident.state = one.state
                    taAccident.addTime = one.addTime
                    accidentMapper.updateByPrimaryKey(taAccident)
                } else {
                    log.debug("APP上传案件")
                    TaAccidentReport().apply {
                        this.accidentId = taAccident.id
                        accidentReportMapper.selectOne(this)?.let {
                            regionId = it.xzqh
                            if (taAccident.subType == 1) {
                                //此处须手动调用同一
                                accidentService.policeAccept(1, it.id!!)
                            }
                            TaAccidentReportAssign().apply {
                                this.accidentReportId = it.id
                                this.assignedPoliceNumber = police_number
                                this.hasAccepted = 1
                                accidentReportAssignMapper.selectOne(this)?.let {
                                    if (it.reportSource == 2) {
                                        this.assignedPoliceNumber = null
                                        accidentReportAssignMapper.select(this).apply {
                                            for (taAccidentReportAssign in this) {
                                                taAccidentReportAssign.reportSource = 3
                                                accidentReportAssignMapper.updateByPrimaryKeySelective(taAccidentReportAssign)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    taAccident.state = 3
                    taAccident.policeReportTime = Date()
                    accidentMapper.updateByPrimaryKeySelective(taAccident)
                    var monitorMap: HashMap<String, Any?> = hashMapOf<String, Any?>()
                    monitorMap.put("regionId", regionId)
                    if (taAccident.dealType as Int == 1) {// 受理
                        monitorMap.put("dealAccepted", 1)
                    } else if (taAccident.dealType as Int == 2) {// 快赔
                        monitorMap.put("dealFastPay", 1)
                    } else if (taAccident.dealType as Int == 3) {// 自行协商
                        monitorMap.put("dealToNegotiate", 1)
                    } else if (taAccident.dealType as Int == 4) {// 其他
                        monitorMap.put("dealOthers", 1)
                    }
                    taPoliceSituationMonitoringService.doMonitorAction(monitorMap)
                }
            } else {
                log.debug("第三方上传责任书")
                taAccident.state = 4
                taAccident.paperTime = Date()
                accidentMapper.updateByPrimaryKeySelective(taAccident)
            }
            return ResultTo().apply {
                this["taAccidentId"] = taAccident.id!!
            }
        }
        log.info("ID为Null")
        return ResultTo(ResultEnum.PARAM_ERROR)
    }

    @Transactional
    override fun webEditAccident(editAccidentVo: EditAccidentVo, isAddPaper: Boolean): ResultTo {
        //TODO:
        log.info("收到数据:${JSON.toJSONString(editAccidentVo)}")
        val resultTo = policeAddReport(editAccidentVo as PoliceAddReportVo, isAddPaper, true)
        if (resultTo[ResultTo.RESULT_CODE] == 0) {
            editAccidentVo.personnelList?.apply {

                TaAccidentPersonnel()?.apply {
                    accidentId = editAccidentVo.id
                    /*accidentPersonnelMapper.select(this)?.apply {
                        val old = BeanUtil.listField2Set("id", this)
                        val new = BeanUtil.listField2Set("id", this@apply)
                        old.removeAll(new).let {
                            for (any in old) {
                                accidentPersonnelMapper.deleteByPrimaryKey(any)
                            }
                        }
                    }*/
                }

                accidentPersonnelMapper.delete(TaAccidentPersonnel().apply { this.accidentId = editAccidentVo.id })
                for (accidentPersonnel in this) {
                    accidentPersonnel.accidentId = editAccidentVo.id
                    accidentPersonnelMapper.insertSelective(accidentPersonnel)
                    /*if (accidentPersonnel.id == null) {
                        accidentPersonnel.accidentId = editAccidentVo.id
                        accidentPersonnelMapper.insertSelective(accidentPersonnel)
                    } else {
                        accidentPersonnelMapper.updateByPrimaryKey(accidentPersonnel)
                    }*/
                }
            }


            editAccidentVo.vehicleList?.apply {
                TaAccidentVehicle().apply {
                    accidentId = editAccidentVo.id
                    /*accidentVehicleMapper.select(this)?.apply {
                        val old = BeanUtil.listField2Set("id", this)
                        val new = BeanUtil.listField2Set("id", this@apply)
                        old.removeAll(new).let {
                            for (any in old) {
                                accidentVehicleMapper.deleteByPrimaryKey(any)
                            }
                        }
                    }*/
                }

                accidentVehicleMapper.delete(TaAccidentVehicle().apply { this.accidentId = editAccidentVo.id })
                for (accidentVehicle in this) {
                    accidentVehicle.accidentId = editAccidentVo.id
                    accidentVehicleMapper.insertSelective(accidentVehicle)
                    /*if (accidentVehicle.id == null) {
                        accidentVehicle.accidentId = editAccidentVo.id
                        accidentVehicleMapper.insertSelective(accidentVehicle)
                    } else {
                        accidentVehicleMapper.updateByPrimaryKey(accidentVehicle)
                    }*/
                }
            }
            accidentImageMapper.delete(TaAccidentImage().apply { this.accidentId = editAccidentVo.id })
            editAccidentVo.images?.forEach { c ->
                c.accidentId = editAccidentVo.id
                c.addTime = Date()
                accidentImageMapper.insertSelective(c)
            }
            return ResultTo()
        } else {
            return resultTo
        }
    }

    override fun policeAddReportImage(taAccidentImage: TaAccidentImage): ResultTo {
        taAccidentImage.addTime = Date()
        accidentImageMapper.insertSelective(taAccidentImage)
        return ResultTo()
    }


    override fun list(page_index: Int?, page_size: Int?, map: MutableMap<String, Any>): ResultTo {
        PageHelper.startPage<Any>(page_index ?: 1, page_size ?: 20)
        if (ManagerKit.isCaptain() || ManagerKit.isOutside()) {
            map["isCaptain"] = true
//            map["orgNum"] = ManagerKit.getOrgNum()
            map["orgNum"] = taPoliceService.consRegion(ManagerKit.getOrgNum()) as String
        } else {
            map["isCaptain"] = false
            map["assigned_police_number"] = ManagerKit.getPoliceNumber()
        }
        map["has_accepted"] = 1
        val list = accidentMapper.list(map)
        val pageInfo = PageInfo(list)
        return ResultTo().apply {
            this["accident_list"] = list
            this["page_index"] = page_index ?: 1
            this["page_amount"] = pageInfo.pages
            this["page_total"] = pageInfo.total
        }
    }

    override fun accidentList(page_index: Int?, page_size: Int?, map: HashMap<String, Any>): ResultTo {
        PageHelper.startPage<Any>(page_index ?: 1, page_size ?: 20)
//        map["orgNum"] = ManagerKit.getOrgNum()
        map["orgNum"] = taPoliceService.consRegion(ManagerKit.getOrgNum()) as String
        val list = accidentMapper.accidentList(map)
        val pageInfo = PageInfo(list)
        return ResultTo().apply {
            this["accident_list"] = list
            this["page_index"] = page_index ?: 1
            this["page_amount"] = pageInfo.pages
            this["page_total"] = pageInfo.total
        }
    }

    override fun detail(id: Int): ResultTo {
        return ResultTo().apply {
            this["accident"] = accidentMapper.selectByPrimaryKey(id)
            val accidentImage = TaAccidentImage()
            accidentImage.accidentId = id
            this["image_url_list"] = accidentImageMapper.select(accidentImage)
            val accidentVehicle = TaAccidentVehicle()
            accidentVehicle.accidentId = id
            this["accident_vehicle"] = accidentVehicleMapper.select(accidentVehicle)
            val accidentPersonnel = TaAccidentPersonnel()
            accidentPersonnel.accidentId = id
            this["accident_personnel"] = accidentPersonnelMapper.select(accidentPersonnel)
        }
    }

    /**
     * 导出excel
     */
    override fun outExcel(map: HashMap<String, Any>, response: HttpServletResponse) {
        map["orgNum"] = ManagerKit.getOrgNum()
        val streetList = streetMapper.selectStreet(map)
        val dateList = dateUtil(map["occur_time_begin"].toString(), map["occur_time_end"].toString())
        val dataList = arrayListOf<ExcelDateVo>()
        for (streetVo in streetList) {
            for (date in dateList) {
                accidentMapper.selectExcelCount(streetVo.streetId, date).apply {
                    val dateVo = ExcelDateVo()
                    dateVo.districtName = streetVo.districtName
                    dateVo.streetName = streetVo.streetName
                    dateVo.time = date
                    for (countVo in this) {
                        when (countVo.type) {
                            1 -> dateVo.breakCount = countVo.typeCount
                            2 -> dateVo.cutCount = countVo.typeCount
                            3 -> dateVo.deathCount = countVo.typeCount
                            4 -> dateVo.otherCount = countVo.typeCount
                        }
                    }
                    if (dateVo.breakCount != 0 || dateVo.cutCount != 0 || dateVo.deathCount != 0 || dateVo.otherCount != 0) {
                        dataList.add(dateVo)
                    }
                }
            }
        }
        log.info("outExcel->" + dataList.toString())
        ExcelUtil.exportExcel(dataList, "交通统计", "sheet1", ExcelDateVo::class.java, UUID.randomUUID().toString(), response)
    }

    /**
     * 获取位置信息
     */
    override fun selectPosition(accident: TaAccident, isTiming: Boolean) {
        if (StringUtils.isNotBlank(accident.locationIdList) && StringUtils.isNotBlank(accident.geojsonList)) {
            if (!isTiming) {
                log.info("APP已经传入位置信息")
                PositionApi.ApiBean().apply {
                    this.amapDistrict = accident.amapDistrict
                    this.amapStreet = accident.amapStreet
                    this.amapAddress = accident.amapAddress
                    positionApi.savePosition(this)
                    accident.districtId = this.districtId
                    accident.streetId = this.streetId
                    accident.addressId = this.addressId
                }
                accidentMapper.updateByPrimaryKeySelective(accident)
            }
        } else {
            if (accident.amapLatitude != null && accident.amapLongitude != null) {
                if (!isTiming) {
                    log.info("APP没有传入位置信息")
                    threadPoolTaskExecutor.execute {
                        run {
                            try {
                                positionApi.send(accident.amapLongitude, accident.amapLatitude)?.apply {
                                    updateGeojsonList(this, accident)
                                }
                            } catch (e: Exception) {
                                log.warn("获取位置信息请求发生异常,异常信息:{}", e.message)
                            }
                        }
                    }
                } else {
                    try {
                        positionApi.send(accident.amapLongitude, accident.amapLatitude)?.apply {
                            updateGeojsonList(this, accident)
                        }
                    } catch (e: Exception) {
                        log.warn("获取位置信息请求发生异常,异常信息:{}", e.message)
                    }
                }
            } else {
                log.warn("案件ID:{},现场传入的GPS信息为空", accident.id)
            }
        }
    }

    /**
     * 只针对Id对应的记录更新经纬度
     */
    override fun updateDynamicCoordinates(id: String, longitude: Double, latitude: Double) {
        var taAccident: TaAccident = accidentMapper.selectByPrimaryKey(id)
        taAccident.amapLongitude = longitude
        taAccident.amapLatitude = latitude
        accidentMapper.updateByPrimaryKey(taAccident)
    }

    override fun searchMqMessage(police_number: String): List<TaHmsPush>? {
        return taHmsPushService.searchMqMessage(police_number)
    }


    private fun updateGeojsonList(apiBean: PositionApi.ApiBean, accident: TaAccident) {
        apiBean.apply {
            accident.districtId = this.districtId
            accident.streetId = this.streetId
            accident.addressId = this.addressId
            accident.geojsonList = this.geojsonList
            accident.locationIdList = this.locationIdList
            accidentMapper.updateByPrimaryKeySelective(accident)
        }

    }


    override fun accidentCount(time_begin: String, time_end: String): ResultTo {
        if (!ManagerKit.isCaptain()) {
            return ResultTo(ResultEnum.ILLEGAL_OPERATION)
        }
        val dateList = dateUtil(time_begin, time_end)
        val list = arrayListOf<ExcelCTPoliceVo>()
        for (date in dateList) {
            var OrmResult1 = accidentReportMapper.selectAccidentCount("$date 00:00:00", "$date 23:59:59")
            var OrmResult2 = accidentReportMapper.selectNoticeCount("$date 00:00:00", "$date 23:59:59")
            var OrmResults3 = accidentReportMapper.selectPlatoonCount("$date 00:00:00", "$date 23:59:59")
            var OrmResults4 = accidentReportMapper.selectReceiveCount("$date 00:00:00", "$date 23:59:59")
            var OrmResults5 = accidentReportMapper.selectAcceptCount("$date 00:00:00", "$date 23:59:59")
            ExcelCTPoliceVo().apply {
                this.date = date
                this.accidentCount = OrmResult1
                this.noticeCount = OrmResult2
                val policeAccidents = arrayListOf<PoliceAccident>()
                for (ormResult in OrmResults3) {
                    PoliceAccident().apply {
                        this.name = ormResult.name
                        this.policeNumber = ormResult.policeNumber
                        this.designateAmount = ormResult.count
                        this.acceptAmount = 0
                        this.reportAmount = 0
                        policeAccidents.add(this)
                    }
                }
                for (ormResult in OrmResults4) {
                    var temp = false
                    for (policeAccident in policeAccidents) {
                        if (ormResult.policeNumber == policeAccident.policeNumber) {
                            policeAccident.acceptAmount = ormResult.count
                            temp = true
                            break
                        }
                    }
                    if (!temp) {
                        PoliceAccident().apply {
                            this.name = ormResult.name
                            this.policeNumber = ormResult.policeNumber
                            this.designateAmount = 0
                            this.acceptAmount = ormResult.count
                            this.reportAmount = 0
                            policeAccidents.add(this)
                        }
                    }
                }

                for (ormResult in OrmResults5) {
                    var temp = false
                    for (policeAccident in policeAccidents) {
                        if (ormResult.policeNumber == policeAccident.policeNumber) {
                            policeAccident.reportAmount = ormResult.count
                            temp = true
                            break
                        }
                    }
                    if (!temp) {
                        PoliceAccident().apply {
                            this.name = ormResult.name
                            this.policeNumber = ormResult.policeNumber
                            this.designateAmount = 0
                            this.acceptAmount = 0
                            this.reportAmount = ormResult.count
                            policeAccidents.add(this)
                        }
                    }
                }
                this.policeAccidents = policeAccidents
                list.add(this)
            }
        }
        return ResultTo().setData("data", list)
    }

    override fun searchTaAccidentMapList(map: Map<String, Any?>): List<Map<String, Any?>>? {
        try {
            return accidentMapper.searchTaAccidentMapList(map);
        } catch (e: Exception) {
            log.info("searchTaAccidentMapList: {}", e)
        }
        return null;
    }


    companion object {

        private val FORMAT = SimpleDateFormat("yyyy-MM-dd")

        private val log: Logger = LoggerFactory.getLogger(this::class.java)

        fun dateUtil(beginDate: String, endDate: String): List<String> {
            val d1 = FORMAT.parse(beginDate)//定义起始日期
            val d2 = FORMAT.parse(endDate)//定义结束日期
            val dd = Calendar.getInstance()//定义日期实例
            dd.time = d1//设置日期起始时间
            val list = arrayListOf<String>()
            while (dd.time.before(d2)) {
                val str = FORMAT.format(dd.time)
                list.add(str)
                dd.add(Calendar.DATE, 1)
            }
            list.add(FORMAT.format(dd.time))
            return list
        }
    }


    @OracleDb
    override fun relatedAcdFile(accidentId: Int): ResultTo {
        loadAcdFileDetail()
        return ResultTo()
    }

    override fun relatedLocalFile(accidentId: Int): ResultTo {
        loadAccidentDetail()
        return ResultTo()
    }

    private fun loadAccidentDetail() {
        TaPolice().apply {
            policeNumber = "100001"
            taPoliceMapper.selectOne(this)
        }
    }

    @Autowired
    private lateinit var tAcdFileMapper: OracleTAcdFileMapper

    private fun loadAcdFileDetail() {
        tAcdFileMapper.selectAccidentCLSYXZAmountGroup("T_ACD_FILE", "T_CODE", "T_ACD_FILEHUMAN", "2017-01-01", "2018-01-01", 20)
    }
}